/**
 * 大纲编辑器组件
 * 显示和编辑AI生成的文章大纲
 */

import React, { useState } from 'react'
import {
  Card,
  Input,
  Button,
  Typography,
  Space,
  Tag,
  Tooltip,
  Modal,
  InputNumber,
  Form,
  Alert,
  Badge
} from 'antd'
import {
  EditOutlined,
  PlayCircleOutlined,
  ReloadOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons'
import { 
  ArticleOutline, 
  OutlineSection, 
  OutlineSectionType, 
  SectionStatus 
} from '../../../types/spark'

const { Title, Text, Paragraph } = Typography
const { TextArea } = Input

export interface OutlineEditorProps {
  outline: ArticleOutline | null
  onOutlineChange: (outline: ArticleOutline) => void
  onSectionUpdate: (sectionId: string, updates: Partial<OutlineSection>) => void
  onGenerateContent: (sectionId: string) => void
  onComplete?: () => void
  isLoading?: boolean
}

const OutlineEditor: React.FC<OutlineEditorProps> = ({
  outline,
  onOutlineChange,
  onSectionUpdate,
  onGenerateContent,
  onComplete,
  isLoading = false
}) => {
  const [editingSection, setEditingSection] = useState<OutlineSection | null>(null)
  const [isEditModalVisible, setIsEditModalVisible] = useState(false)
  const [form] = Form.useForm()

  // 如果没有大纲，显示等待状态
  if (!outline) {
    return (
      <div style={{ textAlign: 'center', padding: 48 }}>
        <LoadingOutlined style={{ fontSize: 32, color: '#1890ff' }} />
        <Title level={4} style={{ marginTop: 16, color: '#666' }}>
          正在生成文章大纲...
        </Title>
        <Paragraph style={{ color: '#999' }}>
          AI正在根据您的回答生成详细的文章结构
        </Paragraph>
      </div>
    )
  }

  // 处理标题编辑
  const handleTitleChange = (title: string) => {
    onOutlineChange({
      ...outline,
      title,
      updatedAt: new Date()
    })
  }

  // 打开段落编辑模态框
  const handleEditSection = (section: OutlineSection) => {
    setEditingSection(section)
    form.setFieldsValue({
      title: section.title,
      description: section.description,
      keyPoints: section.keyPoints.join('\n'),
      estimatedLength: section.estimatedLength
    })
    setIsEditModalVisible(true)
  }

  // 保存段落编辑
  const handleSaveSection = async () => {
    try {
      const values = await form.validateFields()
      if (editingSection) {
        const updates: Partial<OutlineSection> = {
          title: values.title,
          description: values.description,
          keyPoints: values.keyPoints.split('\n').filter((point: string) => point.trim()),
          estimatedLength: values.estimatedLength
        }
        onSectionUpdate(editingSection.id, updates)
      }
      setIsEditModalVisible(false)
      setEditingSection(null)
    } catch (error) {
      console.error('保存段落失败:', error)
    }
  }

  // 获取段落类型显示名称
  const getSectionTypeName = (type: OutlineSectionType): string => {
    switch (type) {
      case OutlineSectionType.INTRO:
        return '引言'
      case OutlineSectionType.BODY:
        return '正文'
      case OutlineSectionType.CONCLUSION:
        return '结论'
      default:
        return '段落'
    }
  }

  // 获取段落类型颜色
  const getSectionTypeColor = (type: OutlineSectionType): string => {
    switch (type) {
      case OutlineSectionType.INTRO:
        return 'blue'
      case OutlineSectionType.BODY:
        return 'green'
      case OutlineSectionType.CONCLUSION:
        return 'orange'
      default:
        return 'default'
    }
  }

  // 获取状态图标和颜色
  const getStatusDisplay = (status: SectionStatus) => {
    switch (status) {
      case SectionStatus.PENDING:
        return { icon: <ExclamationCircleOutlined />, color: '#faad14', text: '待生成' }
      case SectionStatus.GENERATING:
        return { icon: <LoadingOutlined />, color: '#1890ff', text: '生成中' }
      case SectionStatus.COMPLETED:
        return { icon: <CheckCircleOutlined />, color: '#52c41a', text: '已完成' }
      case SectionStatus.ERROR:
        return { icon: <ExclamationCircleOutlined />, color: '#ff4d4f', text: '生成失败' }
      default:
        return { icon: <ExclamationCircleOutlined />, color: '#d9d9d9', text: '未知' }
    }
  }

  // 渲染段落卡片
  const renderSectionCard = (section: OutlineSection) => {
    const statusDisplay = getStatusDisplay(section.status)

    return (
      <Card
        key={section.id}
        size="small"
        className={`outline-section ${section.status}`}
        style={{ marginBottom: 12 }}
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Space>
              <Badge
                status={
                  section.status === SectionStatus.COMPLETED ? 'success' :
                  section.status === SectionStatus.GENERATING ? 'processing' :
                  section.status === SectionStatus.ERROR ? 'error' :
                  'default'
                }
                text={
                  <span style={{ fontWeight: 600 }}>{section.title}</span>
                }
              />
              <Tag color={getSectionTypeColor(section.type)}>
                {getSectionTypeName(section.type)}
              </Tag>
            </Space>
            <Space size="small">
              <Text style={{ fontSize: 12, color: '#999' }}>
                预计 {section.estimatedLength} 字
              </Text>
              <Tooltip title="编辑段落">
                <Button
                  type="text"
                  size="small"
                  icon={<EditOutlined />}
                  onClick={() => handleEditSection(section)}
                />
              </Tooltip>
            </Space>
          </div>
        }
      >
        {/* 段落描述 */}
        {section.description && (
          <Paragraph style={{ marginBottom: 8, fontSize: 13, color: '#666' }}>
            {section.description}
          </Paragraph>
        )}

        {/* 关键要点 */}
        {section.keyPoints.length > 0 && (
          <div style={{ marginBottom: 12 }}>
            <Text strong style={{ fontSize: 12, color: '#333' }}>关键要点：</Text>
            <div style={{ marginTop: 4 }}>
              {section.keyPoints.map((point, index) => (
                <Tag key={index} style={{ fontSize: 11, marginBottom: 2 }}>
                  {point}
                </Tag>
              ))}
            </div>
          </div>
        )}

        {/* 操作按钮 */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', marginTop: 8 }}>
          {section.status === SectionStatus.PENDING && (
            <Button
              type="primary"
              size="small"
              icon={<PlayCircleOutlined />}
              onClick={() => onGenerateContent(section.id)}
              disabled={isLoading}
            >
              生成内容
            </Button>
          )}

          {(section.status === SectionStatus.ERROR || section.status === SectionStatus.COMPLETED) && (
            <Button
              size="small"
              icon={<ReloadOutlined />}
              onClick={() => onGenerateContent(section.id)}
              disabled={isLoading}
            >
              重新生成
            </Button>
          )}
        </div>
      </Card>
    )
  }

  // 计算统计信息
  const stats = {
    totalSections: outline.sections.length,
    completedSections: outline.sections.filter(s => s.status === SectionStatus.COMPLETED).length,
    totalWords: outline.totalEstimatedLength,
    completedWords: outline.sections
      .filter(s => s.status === SectionStatus.COMPLETED)
      .reduce((sum, s) => sum + s.estimatedLength, 0)
  }

  const progress = stats.totalSections > 0 ? Math.round((stats.completedSections / stats.totalSections) * 100) : 0

  return (
    <div className="outline-editor">
      {/* 大纲头部 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ marginBottom: 12 }}>
          <Input
            value={outline.title}
            onChange={(e) => handleTitleChange(e.target.value)}
            placeholder="请输入文章标题"
            style={{ fontSize: 18, fontWeight: 600 }}
            bordered={false}
          />
        </div>
        
        {/* 统计信息 */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space size="large">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 18, fontWeight: 600, color: '#1890ff' }}>
                {stats.completedSections}/{stats.totalSections}
              </div>
              <div style={{ fontSize: 12, color: '#999' }}>段落完成</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 18, fontWeight: 600, color: '#52c41a' }}>
                {stats.completedWords}
              </div>
              <div style={{ fontSize: 12, color: '#999' }}>字数完成</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 18, fontWeight: 600, color: '#ff6b35' }}>
                {progress}%
              </div>
              <div style={{ fontSize: 12, color: '#999' }}>整体进度</div>
            </div>
          </Space>
          
          <Space>
            <Button icon={<SettingOutlined />} size="small">
              设置
            </Button>
            {progress === 100 && onComplete && (
              <Button type="primary" onClick={onComplete}>
                开始生成
              </Button>
            )}
          </Space>
        </div>
      </Card>

      {/* 提示信息 */}
      {progress === 0 && (
        <Alert
          message="大纲已生成完成"
          description="您可以编辑各段落的标题、描述和关键要点，然后点击'生成内容'开始创作。"
          type="success"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 段落列表 */}
      <div className="outline-sections">
        {outline.sections
          .sort((a, b) => a.order - b.order)
          .map(renderSectionCard)}
      </div>

      {/* 段落编辑模态框 */}
      <Modal
        title="编辑段落"
        open={isEditModalVisible}
        onOk={handleSaveSection}
        onCancel={() => setIsEditModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="段落标题"
            rules={[{ required: true, message: '请输入段落标题' }]}
          >
            <Input placeholder="请输入段落标题" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="段落描述"
          >
            <TextArea
              placeholder="请描述这个段落的主要内容"
              autoSize={{ minRows: 2, maxRows: 4 }}
            />
          </Form.Item>
          
          <Form.Item
            name="keyPoints"
            label="关键要点"
            help="每行一个要点"
          >
            <TextArea
              placeholder="请输入关键要点，每行一个"
              autoSize={{ minRows: 3, maxRows: 6 }}
            />
          </Form.Item>
          
          <Form.Item
            name="estimatedLength"
            label="预计字数"
            rules={[{ required: true, message: '请输入预计字数' }]}
          >
            <InputNumber
              min={50}
              max={2000}
              placeholder="预计字数"
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default OutlineEditor